package com.example.weight.greenSeasons.others;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.greenSeasons.deodorization.DeodorizationTower;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class FlyMouseCraft extends AppCompatActivity {
    //用户、抄表人
    private String name, factory;
    private TextView dateText;
    private EditText flyPoisonName, flyPoisonNum, mousePoisonName, mousePoisonNum, zhangPoisonName, zhangPoisonNum,comment;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date editDate = new Date(System.currentTimeMillis());
    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fly_mouse_craft);

        //用户和职责
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar = findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) { finish(); }
            @Override
            public void onTitleClick(View v) {}
            @Override
            public void onRightClick(View v) {}
        });

        dateText = findViewById(R.id.fly_mouse_craft_date);
        dateText.setText(simpleDateFormat.format(editDate));

        flyPoisonName = findViewById(R.id.fly_poison_name);
        flyPoisonNum = findViewById(R.id.fly_poison_num);
        mousePoisonName = findViewById(R.id.mouse_poison_name);
        mousePoisonNum = findViewById(R.id.mouse_poison_num);
        zhangPoisonName = findViewById(R.id.zhang_poison_name);
        zhangPoisonNum = findViewById(R.id.zhang_poison_num);
        comment = findViewById(R.id.fly_mouse_comment);

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/sjqFlyratProcess/getlast?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                new AlertDialog.Builder(FlyMouseCraft.this)
                                        .setTitle("今日已填写此表")
                                        .setCancelable(false)
                                        .setPositiveButton("确定", null)
                                        .show();
                                JSONObject data = jsonObject.getJSONObject("data");
                                flyPoisonName.setText(data.getString("fliesDrugName"));
                                flyPoisonNum.setText(data.getString("fliesDrugDose"));
                                mousePoisonName.setText(data.getString("ratsDrugName"));
                                mousePoisonNum.setText(data.getString("ratsDrugDose"));
                                zhangPoisonName.setText(data.getString("cockroachDrugName"));
                                zhangPoisonNum.setText(data.getString("cockroachDrugDose"));
                                comment.setText(data.getString("remarks"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(FlyMouseCraft.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    //    选择日期
    @SuppressLint({"DefaultLocale", "ResourceType"})
    public void selectDate(View view){
        int YEAR = calendar.get(Calendar.YEAR);
        int MONTH = calendar.get(Calendar.MONTH);
        int DAY = calendar.get(Calendar.DAY_OF_MONTH);
        new DatePickerDialog(this, 2, (view1, year, month, day) -> {
            // 更新EditText控件日期 小于10加0
            dateText.setText(new StringBuilder()
                    .append(year)
                    .append("-")
                    .append((month + 1) < 10 ? "0"+ (month + 1) : (month + 1))
                    .append("-")
                    .append((day < 10) ? "0" + day : day));
        },YEAR, MONTH, DAY).show();
    }

    public void save(View view) {
        if (flyPoisonName.getText().toString().equals("")) {
            Toast.makeText(this, "请填写灭蝇药剂名称", Toast.LENGTH_SHORT).show();
            return;
        }
        if (flyPoisonNum.getText().toString().equals("")) {
            Toast.makeText(this, "请填写灭蝇药剂使用量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mousePoisonName.getText().toString().equals("")) {
            Toast.makeText(this, "请填写灭鼠药剂名称", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mousePoisonNum.getText().toString().equals("")) {
            Toast.makeText(this, "请填写灭鼠药剂使用量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (zhangPoisonName.getText().toString().equals("")) {
            Toast.makeText(this, "请填写灭蟑药剂名称", Toast.LENGTH_SHORT).show();
            return;
        }
        if (zhangPoisonNum.getText().toString().equals("")) {
            Toast.makeText(this, "请填写灭蟑药剂使用量", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/sjqFlyratProcess/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2"))
                                            Toast.makeText(FlyMouseCraft.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(FlyMouseCraft.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(FlyMouseCraft.this, "保存失败", Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("date", dateText.getText().toString());
                            map.put("flies_drug_name", flyPoisonName.getText().toString());
                            map.put("flies_drug_dose", flyPoisonNum.getText().toString());
                            map.put("rats_drug_name", mousePoisonName.getText().toString());
                            map.put("rats_drug_dose", mousePoisonNum.getText().toString());
                            map.put("cockroach_drug_name", zhangPoisonName.getText().toString());
                            map.put("cockroach_drug_dose", zhangPoisonNum.getText().toString());
                            map.put("factory", factory);
                            map.put("remarks", comment.getText().toString());
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
}